/*
 * This file is an example of how to embed web-server functionality
 * into existing application.
 * Compilation line:
 * cc example.c shttpd.c -DEMBEDDED
 */

#ifdef _WIN32
#include <winsock.h>
#define	snprintf			_snprintf
#pragma comment(lib,"ws2_32")
#else
#include <sys/types.h>
#include <sys/select.h>
#endif

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <time.h>

#include "shttpd.h"

static int
index_html(struct shttpd_callback_arg *arg)
{
	static int	cnt;
	int		n = 0;
	const char	*fname = NULL, *data = NULL;
	FILE		*fp;

	n += snprintf(arg->buf + n, arg->buflen - n, "%s",
	    "HTTP/1.1 200 OK\r\n"
	    "Content-Type: text/html\r\n"
	    "\r\n"
	    "<html><body>");
	
	n += snprintf(arg->buf + n, arg->buflen - n,
	    "<p>This example shows that it is possible to POST "
	    "big volumes of data to the embedded "
	    "<a href=\"http://shttpd.sourceforge.net\">SHTTPD</a>."
	    "<p>This page has been called %d times</p>", ++cnt);
	
	/* Save POSTed data */
	if ((fname = shttpd_get_var(arg->connection, "filename")) != NULL) {
		if ((fp = fopen(fname, "w+")) != NULL) {
			if ((data = shttpd_get_var(arg->connection,
			    "data")) == NULL) {
				n += snprintf(arg->buf + n, arg->buflen - n,
			    	    "<p>Could not get data</p>");
			} if (fwrite(data, strlen(data), 1, fp) != 1) {
				n += snprintf(arg->buf + n, arg->buflen - n,
			    	    "<p>Could not write data: %s</p>",
				    strerror(errno));
			}
			(void) fclose(fp);
		} else {
			n += snprintf(arg->buf + n, arg->buflen - n,
			    "<p>Error opening %s: %s</p>",
			    fname, strerror(errno));
		}
	}
	
	n += snprintf(arg->buf + n, arg->buflen - n,
	    "<form method=\"post\">"
	    "<p>Enter file name to store POSTed data: "
	    "<input type=\"text\" name=\"filename\" value=\"%s\">"
	    "<p>Data to be stored:<br>"
	    "<textarea cols=68 rows=25 name=\"data\"></textarea><br>"
	    "<input type=\"submit\"></form></body></html>",
	    fname ? fname : "");

	return (n);
}

int main(int argc, char *argv[])
{
	int		sock;
	
	/* Get rid of warnings */
	argc = argc;
	argv = argv;
	
	/* Initialize and setup URLs we gonna serve */
	shttpd_init(NULL);
	shttpd_register_url("/", &index_html, NULL);

	/* Open listening socket */
	sock = shttpd_open_port(9000);

	/* Serve connections infinitely until someone kills us */
	for (;;)
		shttpd_poll(sock, 200);

	/* Probably unreached, because we will be killed by signal */
	shttpd_fini();

	return (EXIT_SUCCESS);
}
